package com.sfh.sfhshopweb.controller;

import com.sfh.sfhshopweb.dto.ResponseResult;
import com.sfh.sfhshopweb.entity.Category;
import com.sfh.sfhshopweb.entity.Goods;
import com.sfh.sfhshopweb.service.ICategoryService;
import com.sfh.sfhshopweb.service.IGoodsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/goods")
@Api(tags = "商品管理")
public class GoodsController {

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private ICategoryService categoryService;

    @PostMapping
    @ApiModelProperty(value = "添加商品")
    public ResponseResult<Boolean> addGoods(Goods goods) {
        goods.setId(null);
        return ResponseResult.success(goodsService.save(goods));
    }

    @PostMapping("/list")
    @ApiOperation(value = "获取商品列表")
    public ResponseResult<List<Goods>> getGoodsList() {
        List<Goods> list = goodsService.list();
        list.forEach(each -> {
            each.setCoverPic(goodsService.getGoodsCoverPic(each.getPicKey()));
        });
        return ResponseResult.success(list);
    }

    @PostMapping("/search")
    @ApiOperation(value = "全局搜索商品")
    public ResponseResult<List<Goods>> globalSearch(@RequestParam("keyword") String keyword) {
        List<Goods> goods = goodsService.searchGoodsByKeyword(keyword);
        return ResponseResult.success(goods);
    }

    @PostMapping("/getOne")
    @ApiOperation(value = "获取商品详情")
    public ResponseResult<Goods> getGoods(String id) {
        Goods goods = goodsService.getById(id);
        return ResponseResult.success(goods);
    }



    @PostMapping("/getCategoryTree")
    @ApiOperation(value = "获取商品分类树")
    public ResponseResult<List<Category>> getCategoryTree() {
        List<Category> category = categoryService.getCategoryTree();
        return ResponseResult.success(category);
    }

    @PostMapping("/getCategoryById")
    @ApiOperation(value = "根据id获取商品分类")
    public ResponseResult<Category> getCategoryById(Integer id) {
        Category category = categoryService.getOne(id);
        return ResponseResult.success(category);
    }

    @PostMapping("/getGoodsByCategoryId")
    @ApiOperation(value = "根据分类id获取商品")
    public ResponseResult<List<Goods>> getGoodsByCategoryId(Integer categoryId) {
        List<Goods> goods = categoryService.getGoodsByCategoryId(categoryId);
        return ResponseResult.success(goods);
    }
}
